/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.vod.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 *
 * @author dRazanakoto
 */
public class ReceiverMulticast extends Receiver {

    private MulticastSocket socket;
    private final int BUFFER_SIZE = 1024; 

    /**
     *
     * @param ip
     * @param port
     */
    public ReceiverMulticast(InetAddress ip, int port) throws Exception {
        super(ip, port);
        socket = new MulticastSocket(port);
        socket.joinGroup(ip);
        if(socket.isConnected())
        	System.out.println("Multicast Connecté");
        if(socket.isBound())
        	System.out.println("socket bound");
        
    }

    @Override
    public String receive() throws Exception {
        byte[] bytes = new byte[BUFFER_SIZE];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
        socket.receive(packet);
        return new String(packet.getData()).trim();
    }

	@Override
	public DatagramPacket receive(int heartbeatSleep) throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
        socket.setSoTimeout(heartbeatSleep);
        try {
			socket.receive(packet);
		} catch (IOException e) {
			socket.setSoTimeout(0);
			throw e;
		}
        socket.setSoTimeout(0);
        return packet;
        //return new String(packet.getData(),"UTF-8");
	}

	@Override
	public String receiveTimeOut(int timeOut) {
		byte[] bytes = new byte[BUFFER_SIZE];
		String msg = "";
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
		try{
			socket.setSoTimeout(timeOut);
			socket.receive(packet);
			msg = new String(packet.getData()).trim();
			socket.setSoTimeout(0);
		}catch(Exception e){
			return "";
		}
        return msg;
	}
}
